package com.example.myshopping3.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.myshopping3.commons.CurUser;
import com.example.myshopping3.exceptions.BadPasswordException;
import com.example.myshopping3.exceptions.LockedException;
import com.example.myshopping3.exceptions.UserNameNotFoundException;
import com.example.myshopping3.mapper.UserMapper;
import com.example.myshopping3.model.User;
import com.example.myshopping3.service.UserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{
    @Override
    public CurUser login(String userName, String userPassword) throws BadPasswordException, LockedException, UserNameNotFoundException {
        //通过userName获得用户信息
        User user = this.getOne(new QueryWrapper<User>().eq("user_name", userName));
        //检测用户名是否存在
        if(user == null){
            throw new UserNameNotFoundException();
        }
        //检测用户是否被冻结
        if(user.getUserStatus() == -1){
            throw new LockedException();
        }
        //验证密码是否正确
        //创建密码器对象
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //判断密码是否正确
        if(passwordEncoder.matches(userPassword,user.getUserPassword())){
            //将用户相关信息封装到CurUser对象中并返回
            CurUser curUser = new CurUser();
            curUser.setUserId(user.getUserId());
            curUser.setUserName(user.getUserName());
            return curUser;
        }else{
            throw new BadPasswordException();
        }

    }
}
